#!/bin/sh

# Copyright 2019 Balena Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

#
# Initializes unique filesystem UUIDs
#

# shellcheck disable=SC1091
. /usr/libexec/os-helpers-logging
. /usr/libexec/os-helpers-fs

# Enable module function
fsuuidsinit_enabled() {
    # shellcheck disable=SC2154
    if [ "$bootparam_flasher" = "true" ]; then
        info "Flasher detected. Avoiding filesystem UUIDS initialization."
        return 1
    fi

    # Wait for balena by-state symlinks to come up
    # We only wait for resin-rootA here as we use it right away
    # but we in fact assume the other symlinks are created as well
    # wait4file does $2 loops of 100ms, therefore use 10 * roottimeout
    timeout=${bootparam_roottimeout:-5}
    if ! wait4file "/dev/disk/by-state/resin-rootA" "$((timeout * 10))"; then
        error "Timeout while waiting for resin-root partition to be detected"
        return 1
    fi

    # Check whether UUIDs have already been regenerated
    uuid_prefix="$(get_dev_uuid "/dev/disk/by-state/resin-rootA" | cut -d "-" -f1)"
    if [ "${uuid_prefix}" = "ba1eadef" ]; then
        info "UUIDs already generated so no need to initialize any new ones."
        return 1
    fi
    return 0
}

# Main module function
fsuuidsinit_run() {
    # Only rename the partitions mounted on the initramfs
    # the rest will be done at runtime mount in parallel with system boot
    # Generate new UUIDs - leave resin-rootA last as it will be used to decide re-runs
    for dev in /dev/disk/by-state/resin-rootB /dev/disk/by-state/resin-state /dev/disk/by-state/resin-data /dev/disk/by-state/resin-rootA; do
        uuid="$(get_dev_uuid "${dev}")"
        fstype="$(get_dev_fstype "${dev}")"
        if [ "${uuid}" = "$(get_cmdline_root_uuid)" ]; then
            touch "/run/initramfs/bootparam_root.mux"
        fi
        if regenerate_uuid "${dev}" "${fstype}"; then
            if [ -f "/run/initramfs/bootparam_root.mux" ]; then
                bootparam_root="UUID=$(get_dev_uuid "${dev}")"
                echo "${bootparam_root}" > /run/initramfs/bootparam_root
                rm -f "/run/initramfs/bootparam_root.mux"
                info "Using new root UUID: ${bootparam_root}"
            fi
        else
            error "UUIDs not regenerated - retry on next boot"
            return
        fi
    done
    info "Unique filesystem UUIDs generated."
}
